package com.bigkoo.pickerviewdemo.slice;

import com.bigkoo.pickerview.Utils.ResUtil;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerviewdemo.ResourceTable;
import com.bigkoo.pickerviewdemo.bean.JsonBean;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.utils.Color;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.ResourceManager;
import ohos.utils.zson.ZSONArray;

import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JsonDataAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static boolean isLoaded = false;
    EventRunner eventRunner = EventRunner.getMainEventRunner();
    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    EventHandler mHandler = new EventHandler(eventRunner) {
        @Override
        public void processEvent(InnerEvent event) {
            switch (event.eventId) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        ResUtil.displayToast(getContext(), "Begin Parse Data");
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    ResUtil.displayToast(getContext(), "Parse Succeed");
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    ResUtil.displayToast(getContext(), "Parse Failed");
                    break;
            }
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        ComponentContainer rootLayout = (ComponentContainer)
                LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_ability_json_data, null, false);
        ResUtil.findViewById(rootLayout, ResourceTable.Id_btn_data).setClickedListener(this);
        ResUtil.findViewById(rootLayout, ResourceTable.Id_btn_show).setClickedListener(this);
        super.setUIContent(rootLayout);
    }

    @Override
    public void onClick(Component v) {
        switch (v.getId()) {
            case ResourceTable.Id_btn_data:
                mHandler.sendEvent(MSG_LOAD_DATA);
                break;
            case ResourceTable.Id_btn_show:
                if (isLoaded) {
                    showPickerView();
                } else {
                    ResUtil.displayToast(getContext(), "Please waiting until the data is parsed");
                }
                break;
        }
    }


    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, Component v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                ResUtil.displayToast(getContext(), tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK.getValue())
                .setTextColorCenter(Color.BLACK.getValue()) //设置选中项文字颜色
                .setContentTextSize(20)
                .isDialog(true)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private ArrayList<JsonBean> parseJson(String jsonFilePath) {
        ArrayList<JsonBean> detail = new ArrayList<>();
        ResourceManager manager = getContext().getResourceManager();
        RawFileEntry rawFileEntry = manager.getRawFileEntry(jsonFilePath);
        //create JsonReader object and pass it the json file,json source or json text.
        try (JsonReader jsonReader = new JsonReader(
                new InputStreamReader(
                        rawFileEntry.openRawFile(), StandardCharsets.UTF_8))) {
            Gson gson = new GsonBuilder().create();
            jsonReader.beginArray(); //start of json array
            while (jsonReader.hasNext()) { //next json array element
                JsonBean entity = gson.fromJson(jsonReader, JsonBean.class);
                detail.add(entity);
            }
            jsonReader.endArray();
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEvent(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "entry/resources/rawfile/province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseJson("entry/resources/rawfile/province.json");//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEvent(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            ZSONArray data = new ZSONArray(Collections.singletonList(result));
            Gson gson = new Gson();
            for (int i = 0; i < data.size(); i++) {
                JsonBean entity = gson.fromJson(data.getZSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEvent(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (mHandler != null) {
            mHandler.removeAllEvent();
        }
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
